<template>
  <div class="main">
    <div class="pl_text">
      <span class="title">批量设置</span>
      <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(0)">市场价</button>
      <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(1)">碧选价</button>
      <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(2)">最高佣金</button>
      <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(3)">上架</button>
      <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(4)">图片</button>
    </div>
    <el-table v-loading="listLoading" element-loading-text="给我一点时间" border :data="list" @selection-change="handleSelectionChange"
      highlight-current-row style="width: 100%">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="图片" width="160px">
        <template slot-scope="scope">
          <MyUpload v-model="scope.row.picSet" :limit='2'/>
        </template>
      </el-table-column>
      <el-table-column prop="skuId" label="SKU码">
      </el-table-column>
      <el-table-column prop="erpColorValue" label="ERP颜色">
      </el-table-column>
      <el-table-column prop="erpSizeId" label="ERP规格">
      </el-table-column>
      <el-table-column v-for="(it, idx) in catArr" :key="idx" :label="it.name" :prop="it.name">
      </el-table-column>

      <el-table-column prop="price" label="市场价格" width="120px">
        <template slot-scope="scope">
          <!-- <el-input type="text" v-model="scope.row.price" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
          <div class="el-form-item__error" style="top: 60%;display: none"></div> -->
          <el-form-item :prop="'goodsSkuList['+scope.$index+'].price'" :rules="commonRules.priceRule" style="margin: 30px 0">
            <el-input type="number" v-model="scope.row.price" style="width: 100%"></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="lanPrice" label="碧选价" width="120px">
        <template slot-scope="scope">
          <!-- <el-input type="text" v-model="scope.row.lanPrice" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
          <div class="el-form-item__error" style="top: 60%;display: none"></div> -->
          <el-form-item :prop="'goodsSkuList['+scope.$index+'].lanPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
            <el-input type="number" v-model="scope.row.lanPrice" style="width: 100%"></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="maxCommission" label="最高佣金" width="120px">
        <template slot-scope="scope">
          <!-- <el-input type="text" v-model="scope.row.maxCommission" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
          <div class="el-form-item__error" style="top: 60%;display: none"></div> -->
            <el-form-item :prop="'goodsSkuList['+scope.$index+'].maxCommission'" :rules="commonRules.priceRule" style="margin: 30px 0">
              <el-input type="number" v-model="scope.row.maxCommission" style="width: 100%"></el-input>
            </el-form-item>
        </template>

      </el-table-column>
      <el-table-column prop="regionPrice" label="大区价">
      </el-table-column>
      <el-table-column prop="directorPrice" label="董事价">
      </el-table-column>
      <el-table-column prop="totalStock" label="库存">
      </el-table-column>
      <el-table-column prop="hasSale" label="已售">
      </el-table-column>
      <el-table-column prop="upShelf" label="是否上架" width="160px">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.upShelf" active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="操作" fixed="right" width="130px">
        <template slot-scope='{row, $index}'>
          <el-button @click="bindCat(row, $index)">关联规格</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="关联规格" :visible.sync="dialogVisible" width="50%">
      <el-form ref="form" label-width="100px">
        <el-form-item label="ERP规格：">
          <span>{{currentSpecErpSizeId}}</span>
        </el-form-item>
        <!-- <el-form-item label="已选SKU:">
          <div class="el-tag-box">
            <el-tag v-for="(item, index) of haveChosen" :key="index" :closable="true" @close="delItem(index)">{{item.name}}</el-tag>
          </div>
        </el-form-item> -->
        <el-form-item label="关联SKU:" style="margin-top:20px">
          <el-select v-model="currentSpecOption" multiple placeholder="请选择">
            <el-option-group v-for="(group, idx) in options" :key="idx" :label="group.label">
              <el-option v-for="(item, idx2) in group.children" @click.native="handleChangeSku(group.label,item, idx)" :disabled="item.disabled"
                :key="idx2" :label="item.label" :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
          <!-- <el-cascader :options="options" v-model="currentSpec.option" :show-all-levels="false"></el-cascader> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParams">取 消</el-button>
        <el-button type="primary" @click="chooseCat">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="批量操作" :visible.sync="batchVisible" width="40%">
      <template v-if="batchType === 0">
        <span>市场价：</span>
        <el-input style="width:200px" placeholder="请输入市场价格" v-model="batchVal" />
      </template>
      <template v-if="batchType === 1">
        <span>碧选价：</span>
        <el-input style="width:200px" placeholder="请输入碧选价" v-model="batchVal" />
      </template>
      <template v-if="batchType === 2">
        <span>最高佣金：</span>
        <el-input style="width:200px" placeholder="请输入最高佣金" v-model="batchVal" />
      </template>
      <template v-if="batchType === 3">
        <span>上架：</span>
        <el-switch v-model="batchVal" active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0">
        </el-switch>
      </template>
      <template v-if="batchType === 4">
        <span>上传图片：</span>
        <MyUpload v-model="batchVal" />
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParams">取 消</el-button>
        <el-button type="primary" @click="submitBatch">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MyUpload from '@/components/Upload/myUpload'
// 规格明细
export default {
  props: {
    goodsSkuList: {
      type: Array,
      default() {
        return []
      }
    },
    catArr: {
      type: Array,
      default() {
        return []
      }
    }
  },
  components: {
    MyUpload
  },
  data() {
    return {
      listLoading: false,
      list: this.goodsSkuList,
      dialogVisible: false,
      batchVisible: false, // 批量操作弹框
      batchVal: '', // 批量操作的值
      batchType: '', // 当前批量操作的类型  0 市场加 1 碧选价格 2最高佣金 3 上下架 4 图片
      currnetIdx: 0, //当前操作行
      options: [], // 关联规格级联选择框数据源
      multipleSelection: [], // 批量选择
      currentSpecErpSizeId: '', // 当前规格ERPid
      currentSpecOption: [], // 当前关联规格值
      fromOther: false
    }
  },
  created() {
    this.initAttrProp()
  },
  methods: {
    // 初始化自定义属性 从数据列表中遍历属性组中没有的属性。
    initAttrProp() {
      // const list = JSON.parse(JSON.stringify(this.goodsSkuList))
      this.list = this.list.map(it => {
        let { attrInfo } = it
        if (attrInfo) {
          attrInfo.forEach(val => {
            it[val.attrName] = val.attrValue
          })
        } else {
          it.attrInfo = []
        }
        return it
      })
    },
    //批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 展示批量操作弹框
    showBatch(val) {
      this.batchVisible = true
      this.batchType = val
    },
    // 批量操作
    submitBatch() {
      const keys = ['price', 'lanPrice', 'maxCommission', 'upShelf', 'picSet']
      if (this.batchType < 3){
        const rex = /^[0-9]+(\.\d+)?$/
        if (!rex.test(this.batchVal)){
          this.$message.error("价格只能是大于等于零")
          return
        }
      }
      this.multipleSelection.forEach(item => {
        const index = this.list.findIndex(i => i.id === item.id)
        if (index  >= 0) {
          if (keys[this.batchType] === 'picSet') {
            this.fromOther = true
            this.$set(this.list[index], 'picSet', [this.batchVal])
          } else {
            this.list[index][keys[this.batchType]] = this.batchVal
            this.setPrice(index)
          }
        }
      })
      setTimeout(() => {
        this.batchVal = ''
        this.batchVisible = false
        this.fromOther = false
      }, 500)
    },
    chooseCat() {
      const option = this.currentSpecOption
      if (!option) {
        this.$message.error('请选择关联规格')
        return
      }
      if (option.length < this.catArr.length) {
        this.$message.error('请选择'+ this.catArr.length+'种关联规格')
        return
      }

      // 判断是否选择过
      let hasChoice = false
      for(let i=0;i<this.list.length;i++){
        if (i !== this.currnetIdx && this.list[i].attrInfo.length > 0) {
          let hasNum = 0
          this.list[i].attrInfo.forEach(item => {
            const val = item.attrName + ':' + item.attrValue
            if (option.includes(val) ) hasNum += 1
          })
          if (hasNum === this.list[i].attrInfo.length) {
            hasChoice = true
          }
        }
      }
      if (hasChoice) {
        this.$message.error('选择的规格已存在')
        return
      }

      this.catArr.forEach(item => {
        if (this.list[this.currnetIdx][item.name]) {
          delete this.list[this.currnetIdx][item.name]
        }
      })
      this.list[this.currnetIdx].attrInfo = []

      option.forEach(it => {
        const [prop, value] = it.split(':') // 取出级联选择器的值， 第一位为表格属性 第二位为表格值
        this.list[this.currnetIdx][prop] = value  // 赋值sku操作
        // attrInfo 自定义属性集合
        let id = this.list[this.currnetIdx].id

        this.list[this.currnetIdx].attrInfo.push({
          attrId: id,
          attrName: prop,
          attrValue: value,
          isPicAttr: 0
        })
      })
      this.currentSpecOption = []
      this.dialogVisible = false
    },
    // 生成已选择tag
    generateHaveChose(idx) {
      this.currentSpecOption = []
      let arr = []
      let val = this.list[idx]
      this.options.forEach(it => {
        // list 存在自定义属性 且有值
        if (it.label in val && val[it.label]) {
          arr.push(`${it.label}:${val[it.label]}`)
        }
      })
      this.currentSpecOption = arr
    },
    // 关联规格
    bindCat(val, idx) {
      if(this.catArr.length <= 0) {
        return this.$message.error('请先选择属性组')
      }
      this.currnetIdx = idx // 记录当前操作索引
      let hasCatIsNull = this.checkCatNoNull()
      if (hasCatIsNull) {
        return this.$message.error('请填写完整自定义属性')
      }
      this.generateCat() // 生成级联选择器数据源
      this.generateHaveChose(idx) // 生成关联规格
      this.currentSpecErpSizeId = val.erpSizeId
      this.dialogVisible = true
    },
    // 检查自定义属性是否有空的， 有空的要添加属性，一般针对手动输入的属性
    checkCatNoNull() {
      for (let val of this.catArr) {
        if (val.inputs.length === 0) {
          return true
        }
        // 手动输入属性框 不能有值为空
        for (let b of val.inputs) {
          if (!b) {
            return true
          }
        }
      }
      return false
    },
    // 生成级联选择器数据源
    generateCat() {
      this.options = [] // 每次生成前 先清空 以防有新的属性值增加
      this.catArr.forEach((it, idx) => {
        // 一级属性项目
        this.options.push({
          label: it.name,
          value: it.name,
          disabled: false
        })
        // 二级属性项目
        if (it.inputs && it.inputs.length > 0) {
          this.options[idx].children = []
          it.inputs.forEach(val => {
            let disabled = false
            this.options[idx].children.push({
              label: `${it.name}:${val}`,
              value: `${it.name}:${val}`,
              disabled
            })
          })
        }
      })
    },
    // 关联sku规格发生变化
    handleChangeSku(prop, val, idx) {
      // 不可点击不做操作
      if (val.disabled) {
        return
      }
      let len = this.currentSpecOption.length // this.currentSpec.option.length
      let arr = [...this.currentSpecOption]
      this.currentSpecOption.forEach((it, i) => {
        // 获取当前属性组 名称
        let a = it.split(':')[0]
        for (let j = i + 1; j < len; j++) {
          // 获取后面的属性组子属性名称 如果有相同的把之前的给删除取后面的
          let b = this.currentSpecOption[j].split(':')[0]
          // 子属第一次出现的idx 和后面第二次出先的相同，那么取后面的，一个规格属性组只能选择一个。
          if (a === b) {
            arr.splice(i, 1)
          }
        }
      })
      this.currentSpecOption = [...arr]
    },
    resetParams() {
      this.dialogVisible = false
      this.currentSpecOption = []
      this.batchVisible = false
      this.batchVal = ''
    },
    changeVal(e, row) {
      const rex = /^[0-9]+(\.\d+)?$/
      const val = e.target.value
      if (!rex.test(val)) {
        e.target.parentNode.parentNode.lastChild.innerHTML = '只能是大于等于0的数字'
        e.target.parentNode.parentNode.lastChild.style.display = 'block'
        e.target.setAttribute('style', 'border: 1px solid#F56C6C')
      } else {
        e.target.parentNode.parentNode.lastChild.innerHTML = ''
        e.target.parentNode.parentNode.lastChild.style.display = 'none'
        e.target.setAttribute('style', '')
      }
      const index = this.list.findIndex(i => i.id === row.id)
      if (index !== -1) {
        this.setPrice(index)
      }
    },
    setPrice(index) {
      if (this.list[index].lanPrice && this.list[index].maxCommission){
        this.list[index].regionPrice = this.list[index].lanPrice  - this.list[index].maxCommission * 0.5    // 大区  大区价=碧选价 - 最高佣金*50%
        this.list[index].directorPrice = this.list[index].lanPrice  - this.list[index].maxCommission * 0.8 // 董事  董事价=碧选价 - 最高佣金*80%
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.pl_text {
  display: flex;
  .title {
    font-size: 14px;
    font-weight: 600;
    margin-right: 10px;
  }
  .txt {
    background: #fff;
    border: none;
    cursor: pointer;
    margin-right: 10px;
  }
}
</style>
